package com.it.process;

import com.it.operator.utils.SourceUtils;
import com.it.pojo.Event;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;

/**
 * keyProcessFunction可以定义定时器.
 *
 * @author code1997
 */
public class KeyProcessFunctionTest {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
        SingleOutputStreamOperator<Event> eventSource = SourceUtils.getEventSource(executionEnvironment);
        eventSource.keyBy(event -> event.user).process(new KeyedProcessFunction<String, Event, String>() {
            @Override
            public void processElement(Event value, KeyedProcessFunction<String, Event, String>.Context ctx, Collector<String> out) throws Exception {
                long curTs = ctx.timerService().currentProcessingTime();
                out.collect(ctx.getCurrentKey() + "的数据到达，到达时间：" + new Timestamp(curTs));
                //数据到达10ms秒之后触发
                ctx.timerService().registerProcessingTimeTimer(curTs + 10L);
                Thread.sleep(10);
            }

            @Override
            public void onTimer(long timestamp, KeyedProcessFunction<String, Event, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
                out.collect(ctx.getCurrentKey() + "的定时器触发，出发时间：" + new Timestamp(timestamp));
            }
        }).print();
        executionEnvironment.execute();

    }
}
